/*
 * @Descripttion: 
 * @version: 
 * @Author: LEO
 * @Date: 2021-05-08 13:08:50
 * @LastEditors: 871387321@qq.com 871387321@qq.com
 * @LastEditTime: 2023-11-15 17:10:49
 */
import React, { useRef, useCallback, useEffect, useState, useMemo } from 'react';
import { PageHeader, Formx, Button, history, units } from '@library';
import { FormxRefProps } from '@library/components/formx/interface';
import Qs from 'query-string';
import WfView from './../../../components/wfView/WfView';
import FormView from './../../../components/formView/FormView';
import Role from './_Role';
import { FormxControlTypes as FCT } from '@library';
import formContentToObj from './../../../utils/formContentToObj';
import { WF_STATUS } from './../data';
import { updateWorkflow, getWorkflow, pubWorkflow, withdraw, findOne } from './../Api';
import { WorkFlowHeadProps } from './../../../interface';
import i18n from "@library/app/i18n";


const i18NT = window.$app.t, required = true;


export default () => {
  const formxRef = useRef<FormxRefProps>(null);
  const query = Qs.parseUrl(window.location.href).query;
  const [details, setDetails] = useState<WorkFlowHeadProps>({} as any);
  const [formId, setFormId] = useState('');

  useEffect(() => {
    if (query.id) {
      getWorkflow(query.id as string).then(result => {
        if (result) {
          setDetails(result);
          setFormId(result.formId);
        }
      });
    }
  }, [query.id]);

  const onSave = useCallback(async () => {
    const formData = await formxRef.current?.validateFields();
    if (!formData.id) {
      const res = await findOne(formData.workflowCode);
      if (res) {
        return units.message.error(i18NT('workflowCode_tip'));
      }
    }

    if (formData.workflowCategoryCode === '20') {
      // formData.businessComment = null;
      formData.businessName = null;
    }

    if (formData) {
      const result = await updateWorkflow({
        ...formData as WorkFlowHeadProps,
        formName: formData._formId?.[0]?.formName
      });

      if (result) {
        if (!formData.id) {
          history.replace('/model/details?id=' + result.id);
          return;
        }

        units.message.success();
        setDetails(result);
      }
    }
  }, []);

  const onPub = useCallback(async () => {
    const formData = await formxRef.current?.validateFields();
    if (formData.workflowCategoryCode === '20') {
      // formData.businessComment = null;
      formData.businessName = null;
    }
    if (formData) {
      const result = await pubWorkflow({
        ...details,
        ...formData,
        status: WF_STATUS.PUB
      } as WorkFlowHeadProps);

      if (result) {
        units.message.success();
        history.push('/model');
      }
    }
  }, [details]);

  const onWithdraw = useCallback(async () => {
    const result = await withdraw(details.id as string);
    if (result) {
      units.message.success();
      history.push('/model');
    }
  }, [details.id]);

  const toEditWf = useCallback(() => {
    history.push('/model/details/workflow?id=' + details.id);
  }, [details.id]);

  const onValuesChange = useCallback((value, allValue) => {
    setFormId(allValue.formId);

    let extra: any = {};
    if (value.hasOwnProperty('formId') || value.workflowCategoryCode === '20') {
      formxRef.current?.setFieldsValue({ businessComment: null, businessName: null });
      extra = { businessComment: null, businessName: null };
    }

    setDetails(prev => ({ ...prev, ...allValue, ...value, ...extra }));
  }, []);

  const formItems = useMemo(() => [
    { name: 'workflowCode', required, disabled: !!query.id, label: i18NT('workflowNumber') },
    { name: 'name', required, label: i18NT('workflowName') },
    { name: 'nameEn', label: i18NT('workflowNameEn') },
    {
      name: 'workflowCategoryCode',
      label: i18NT('workflowCategoryDesc'),
      type: FCT.COMPANY_SELECT,
      required,
      options: {
        code: 'WFL_CATEGORY',
        extra: ['codeDesc:workflowCategoryDesc'],
      },
    },
    {
      name: 'moduleCode',
      label: i18NT('moduleName'),
      type: FCT.SELECT,
      required,
      options: {
        url: '/bk/api/company/CompanyFunction/find',
        fieldNames: { label: i18n.language === 'en' ? 'serviceModuleEnName' : 'serviceModuleName', value: 'serviceModuleCode' },
        extra: ['serviceModuleName:moduleName'],
      },
    },

    {
      name: 'mailConfigId',
      label: i18NT('邮箱配置'),
      type: FCT.SELECT,
      options: {
        url: '/bk/api/company/MailConfig/find',
        fieldNames: { label: "{{from}}-{{authUser}}", value: 'id' },
      },
    },

    // {
    //   name: 'workflowTypeCode',
    //   label: i18NT('workflowType'),
    //   type: FCT.COMPANY_SELECT,
    //   required,
    //   options: {
    //     code: 'WFL_TYPE',
    //     extra: ['codeDesc:workflowTypeName'],
    //   },
    // },
    {
      name: 'formId',
      label: i18NT('/form'),
      type: FCT.MODAL_TABLE,
      required: '{{workflowCategoryCode}}==10',
      options: {
        allowClear: details.workflowCategoryCode !== '10',
        width: 800,
        model: {
          title: i18NT('formDesign'),
          url: '/bk/api/fd/Form/find',
          columns: [
            { dataIndex: 'formName', ellipsis: true, tooltip: true },
            { dataIndex: 'formDesc', ellipsis: true, tooltip: true },
            { dataIndex: 'createdAt', format: 'time' }
          ],
          fieldNames: { label: 'formName', value: 'id' },
          searchFields: ['formName', 'formDesc'],
          searchFieldsText: [i18NT('formName'), i18NT('formDesc')]
        }
      },
    },
    {
      name: 'businessName',
      type: FCT.SELECT,
      ghost: '{{workflowCategoryCode}}!=10',
      required,
      options: {
        url: '/bk/api/fd/Form/findOne',
        fieldNames: { label: 'name', value: 'fieldName' },
        query: '{"where":{"id": {{formId}}}}',
        rtnDataAfter: formContentToObj,
      },
    },
    {
      name: 'businessComment',
      type: formId || details.workflowCategoryCode === '10' ? FCT.SELECT : FCT.INPUT,
      required: details.workflowCategoryCode === '10',
      options: {
        url: '/bk/api/fd/Form/findOne',
        fieldNames: { label: 'name', value: 'fieldName' },
        query: '{"where":{"id": {{formId}}}}',
        rtnDataAfter: formContentToObj,
      },
    }
  ], [details.workflowCode, formId, details.workflowCategoryCode, query.id]);

  return (
    <>
      <PageHeader extra={
        <>
          {!details.status && <Button.Save onClick={onSave} />}
          {details.status === WF_STATUS.NEW && (
            <>
              <Button.Save type='default' onClick={onSave} />
              <Button.Submit onClick={onPub}>{window.$app.t('statusRelease')}</Button.Submit>
            </>
          )}
          {details.status === WF_STATUS.PUB && (
            <Button onClick={onWithdraw}>{window.$app.t('withdraw')}</Button>
          )}
        </>
      } />
      <div className='common-scroll-view'>
        <div className='common-block'>
          <PageHeader title='baseInfo' />
          <Formx
            disabled={details.status === WF_STATUS.PUB}
            onValuesChange={onValuesChange}
            initialValues={details}
            ref={formxRef}
            formItems={formItems} />
        </div>

        <div className='common-block'>
          <PageHeader title='bpmnContent' extra={
            details.status === WF_STATUS.NEW && <Button onClick={toEditWf}>
              {window.$app.t('editWorkflow')}
            </Button>
          } />
          <WfView flat bpmnContent={details.bpmnContent} />
        </div>

        {formId && (
          <div className='common-block'>
            <PageHeader title='formDesign' />
            <FormView disabled isLformHtml formId={formId} />
          </div>
        )}

        {details.id && <Role disabled={details.status === WF_STATUS.PUB} workflowId={details.id} />}
      </div>
    </>
  );
};